package com.ailesson.video.service.impl;

import com.ailesson.common.except.GlobalErrorCodeConstants;
import com.ailesson.common.except.ServiceException;
import com.ailesson.video.entity.VideoEntity;
import com.ailesson.video.model.reply.VideoSimpleReply;
import com.ailesson.video.service.VideoService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;

import com.ailesson.video.mapper.ChapterMapper;
import com.ailesson.video.entity.ChapterEntity;
import com.ailesson.video.service.ChapterService;
import com.ailesson.video.model.req.ChapterQueryReq;
import com.ailesson.video.model.req.ChapterReq;
import com.ailesson.video.model.reply.ChapterReply;
import com.ailesson.common.reply.PageResult;
import cn.hutool.core.collection.CollectionUtil;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, ChapterEntity> implements ChapterService {


    @Autowired
    private VideoService videoService;

    @Override
    public PageResult queryPage(ChapterQueryReq params) {
       Page pageTmp = Page.of(params.getPageNo(),params.getPageSize());
       IPage<ChapterEntity> page = this.page(
               pageTmp,
               new LambdaQueryWrapper<ChapterEntity>().orderByDesc(ChapterEntity::getId)
       );
       List<ChapterReply> replyList = Collections.EMPTY_LIST;
       if (CollectionUtil.isNotEmpty(page.getRecords())){
           replyList = page.getRecords().stream().map(x -> {
               ChapterReply reply = new ChapterReply();
               BeanUtils.copyProperties(x, reply);
               return reply;
           }).collect(Collectors.toList());
       }
       return new PageResult<>(replyList,page.getTotal());
    }

    @Override
    public ChapterReply info(Long id) {
        ChapterEntity entity = this.getById(id);
        if (entity != null){
            ChapterReply reply = new ChapterReply();
            BeanUtils.copyProperties(entity, reply);
            return reply;
        }
        return null;
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    @Override
    public void update(ChapterReq chapter) {
        if (chapter.getId() == null || chapter.getId() <= 0){
            throw new ServiceException(GlobalErrorCodeConstants.ID_EMPTY_ERROR);
        }
        ChapterEntity entity = this.getById(chapter.getId());
        if (entity == null){
            throw new ServiceException(GlobalErrorCodeConstants.NOT_EXISTS_ERROR);
        }
        BeanUtils.copyProperties(chapter, entity);
        this.updateById(entity);
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    @Override
    public Long add(ChapterReq chapter) {
        chapter.setId(null);
        ChapterEntity entity = new ChapterEntity();
        BeanUtils.copyProperties(chapter, entity);
        this.save(entity);
        return entity.getId();
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    @Override
    public void deleteByCourseId(Long id) {
         this.remove(new LambdaUpdateWrapper<ChapterEntity>().eq(ChapterEntity::getCourseId,id));
    }

    @Override
    public List<ChapterReply> getTreeList(Long courseId) {
        List<ChapterEntity> list = this.list(new LambdaQueryWrapper<ChapterEntity>().eq(ChapterEntity::getCourseId, courseId));
        List<VideoEntity> videoEntities = videoService.list(new LambdaQueryWrapper<VideoEntity>().eq(VideoEntity::getCourseId, courseId));
        List<ChapterReply> replyList = list.stream().map(x -> {
            ChapterReply reply = new ChapterReply();
            BeanUtils.copyProperties(x, reply);
            if (CollectionUtil.isNotEmpty(videoEntities)) {
                List<VideoEntity> collect = videoEntities.stream().filter(t -> t.getChapterId().equals(x.getId())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(collect)) {
                    List<VideoSimpleReply> simpleReplies = collect.stream().map(y -> {
                        VideoSimpleReply simpleReply = new VideoSimpleReply();
                        BeanUtils.copyProperties(y, simpleReply);
                        return simpleReply;
                    }).collect(Collectors.toList());
                    reply.setChildren(simpleReplies);
                }
            }
            return reply;
        }).collect(Collectors.toList());
        return replyList;
    }
}